# # 读取文件并打开
# path = r"D:\Project\Codes\Python\project1\test1.txt.gz"
# with open(path, mode="rb") as fd:
#     res = fd.read()
#     print(res)
#     # 将字节转换为十六进制字符串，每个字节占两位，前面补零
#     hex_string = ''.join(f"0x{byte:02x}," for byte in res)
#     print("文件内容以十六进制显示：")
#     print(hex_string)

# import zlib
#
# data = 'aaaaaaa'
# print(len(data))
# print(data)
#
# # 压缩
# compressed_data = zlib.compress(data.encode())  # 注意：这儿要以字节的形式传入
# hex_string = ''.join(f"0x{byte:02x}," for byte in compressed_data)
# print(len(compressed_data))
# print(compressed_data)
# print(hex_string)
#
# # 解压
# new_data = zlib.decompress(compressed_data).decode()
# print(len(new_data))
# print(new_data)

import os
import zlib

path =r"G:\code\Zlib\zlib\YK04V4_0_3"
path1 =r"G:\code\Zlib\zlib\data.txt"

all_flies = []
for root,dirs,files in os.walk(path):
    for file in files:
        filepath = os.path.join(root,file)
        all_flies.append(filepath)

print("共有{}个文件".format(len(all_flies)))

for i in all_flies:
    print("路径为:{}".format(i))

fd1 = open(path1,mode='wt',encoding="utf-8")

for i in all_flies:
    data = []
    with open(i,mode='rb') as fd:
        res = fd.read()
        hex_string = ''.join(f"0x{byte:02x}," for byte in res)
        data.append("文件:{}".format(i))
        data.append("二进制内容:{}".format(hex_string))
        data.append(50*"********")
        print("文件:{}".format(i))
        print("二进制内容:{}".format(hex_string))
        print(50*"***")
        for i in data:
            fd1.write(i)
            fd1.write('\n')
else:
    fd1.close()

# zlib算法压缩
print('压缩')
with open(path1,"rb") as fd:
    bdata = fd.read()
compressed_data = zlib.compress(bdata)
compressed_hex = ''.join(f"0x{byte:02x}," for byte in compressed_data)
print(f"压缩文件之后的二进制长度:{len(compressed_hex)}\n内容:{compressed_hex}")


# zlib算法解压缩
print('解压缩')
new_data = zlib.decompress(compressed_data).decode("utf-8")
print((new_data))

